/* $Id: LoginServlet.java 117 2011-08-22 16:35:13Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.servlets;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import alt.djudge.frontend.server.datatypes.SessionEntry;
import alt.djudge.frontend.server.datatypes.UserEntry;
import alt.djudge.frontend.server.models.SessionsModel;
import alt.djudge.frontend.server.models.UsersModel;
import alt.djudge.frontend.server.utils.Linker;


public class LoginServlet extends AbstractServlet
{
	private static final long serialVersionUID = 1L;
	
	private static final Logger log = Logger.getLogger(LoginServlet.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		req.setCharacterEncoding("UTF-8");
		
		String action = req.getParameter("action");
		if ("login".equals(action))
		{
			UserEntry user = UsersModel.setCurrentUser(req, resp);
			if (user != null && user.getLoginAllowed())
			{
				log.info("User `" + user.getUsername() + "' logged in");
				String returnToUrl = req.getParameter("return");
				resp.sendRedirect((returnToUrl != null ? returnToUrl : Linker.link(""))
						+ "?msg="
						+ URLEncoder.encode("Ви увійшли як "
						+ user.getUsername(), defaultEncoding));
			}
			else if (user != null && !user.getLoginAllowed())
			{
				log.info("Login try from disabled user `" + user.getUsername() + "'");
				String returnToUrl = req.getParameter("repeat");	
				String msg = "Login for user `" + user.getUsername() + "' was disabled";
				String msgEncoded = URLEncoder.encode(msg, defaultEncoding);
				resp.sendRedirect((returnToUrl != null ? returnToUrl : Linker.link(""))
						+ "?msg=" + msgEncoded);
			}
			else
			{
				log.info("Login attempt failed");
				String repeatUrl = req.getParameter("repeat");
				resp.sendRedirect(
						(repeatUrl == null || repeatUrl.length() == 0
								? Linker.link("login.jsp") 
								: repeatUrl)
							+ "?msg="
							+ URLEncoder.encode("Неправильне ім'я користувача або пароль",
						defaultEncoding));
			}
		}
		else if ("register".equals(action))
		{
			String username = req.getParameter("username");
			String password = req.getParameter("password");
			if (username == null || username.length() == 0)
			{
				resp.sendRedirect(
					Linker.link("register.jsp?msg="
						+ URLEncoder.encode("Username should be nonempty",
					defaultEncoding))
				);
				return;
			}
			if (password == null || password.length() == 0)
			{
				resp.sendRedirect(
					Linker.link("register.jsp?msg="
							+ URLEncoder.encode("Password should be nonempty",
					defaultEncoding)));
				return;
			}
			String role = "user";
			log.info("Register: " + username + " " + password);
			if (UsersModel.getUserByUsername(username) == null)
			{
				log.info("Registering: " + username);
				UserEntry newUser = new UserEntry();
				newUser.setActive(true);
				newUser.setUsername(username);
				newUser.setPassword(password);
				newUser.setRole(role);
				newUser.makePersistent();
				UsersModel.setCredentials(req, resp, newUser);
				resp.sendRedirect(Linker.link("?msg=" + URLEncoder.encode("User " + username + " was successfully registerd", defaultEncoding)));
			}
			else
			{
				log.info("User already exists: " + UsersModel.getUserByUsername(username));
				resp.sendRedirect(Linker.link("register.jsp?msg=" + URLEncoder.encode("Username " + username + " already used!!!", defaultEncoding)));
			}
		}
		else if ("logout".equals(action))
		{
			UserEntry user = UsersModel.getCurrentUser(req);
			if (user != null)
			{
				UsersModel.removeCurrentUser(req, resp);
				SessionsModel.deleteUserSessions(user.getId());
			}
			String returnToUrl = req.getParameter("return");
			resp.sendRedirect((returnToUrl != null ? returnToUrl : Linker.link("")));
		}
		else if ("customEdit".equals(action))
		{
			if (req.getParameter("killOldSessions") != null)
			{
				HashMap<String, Object> sessReq = new HashMap<String, Object>();
				sessReq.put("expireTime<", new Date());
				List<SessionEntry> list = SessionsModel.getEntries(sessReq);
				for (SessionEntry entry : list)
					entry.delete();
			}
			if (req.getParameter("killSessions") != null)
			{
				List<SessionEntry> list = SessionsModel.getEntries(new HashMap<String, Object>());
				for (SessionEntry entry : list)
					entry.delete();
			}

		}
	}
}
